package com.shigu.mo.services;

import com.shigu.component.shiro.CaptchaUsernamePasswordToken;
import com.shigu.mo.exceptions.MoException;
import com.shigu.wx.web.*;
import com.shigu.wx.web.services.WxOpenidService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.sword.wechat4j.api.WechatClient;
import java.io.IOException;

/**
 * 用户基础服务
 */
@Service
public class UserBaseService {
    private static final Logger logger = LoggerFactory.getLogger(UserBaseService.class);
    @Value("${wechat.appid}")
    private String APP_ID;

    @Value("${wechat.appsecret}")
    private String APP_SECRET;

    @Autowired
    private WxOpenidService wxOpenidService;


    /**
     * 是否关注
     * @param openid
     * @return
     */
    public boolean hasFollow(String openid,Long userId){
        try {
            return wxOpenidService.createWxinfo(openid,userId)==1;
        } catch (Exception e) {
            logger.error("hasFollow error! openid:"+openid+" userId:"+userId,e);
            return false;
        }
        //查关注状态
    }

    /**
     * 静默登陆
     * @param code
     * @return
     * @throws IOException
     */
    public WebToken mkWebToken(String code){
        WechatClient client = new WechatClient();
        SnsOauth2Access_tokenGet tokenGet = new SnsOauth2Access_tokenGet();
        tokenGet.setAppid(APP_ID);
        tokenGet.setSecret(APP_SECRET);
        tokenGet.setCode(code);
        try {
            return client.execute(tokenGet);
        } catch (Exception e) {
            logger.error("hasFollow error! code:"+code,e);
            return null;
        }
    }

    /**
     * 使用微信openIid实现免登
     * @param openid
     * @return
     * @throws IOException
     * @throws MoException
     */
    public boolean loginByWx(String openid){
        if (StringUtils.isEmpty(openid)) {
            return false;
        }
        Long userId=wxOpenidService.selLogedUserIdByOpenid(openid);
        if (userId == null) {
            return false;
        }
        Subject currentUser = SecurityUtils.getSubject();
        CaptchaUsernamePasswordToken lgtoken = new CaptchaUsernamePasswordToken("default",
                "1", "1", false, "", "");
        lgtoken.setType(1);
        lgtoken.setUserId(userId);
        lgtoken.setRememberMe(true);
        try {
            currentUser.login(lgtoken);
            return true;
        } catch (AuthenticationException e) {
            return false;
        }
    }




}
